// app 模块，它控制应用程序的事件生命周期。
// BrowserWindow 模块，它创建和管理应用程序 窗口。
const { default: installExtension, REACT_DEVELOPER_TOOLS } = require('electron-devtools-installer');
const { app, BrowserWindow, Menu, MenuItem, net, Notification, ipcMain, dialog, nativeTheme } = require('electron');
// 在你文件顶部导入 Node.js 的 path 模块
const path = require('node:path')

const { postRequest } = require('./http');


async function handleFileOpen () {
  const { canceled, filePaths } = await dialog.showOpenDialog()
  if (!canceled) {
    return filePaths[0]
  }
}

let progressInterval;
function progressEvent(win) {
  const INCREMENT = 0.03
  const INTERVAL_DELAY = 100 // ms

  let c = 0
  progressInterval = setInterval(() => {
    // update progress bar to next value
    // values between 0 and 1 will show progress, >1 will show indeterminate or stick at 100%
    win.setProgressBar(c)

    // increment or reset progress bar
    if (c < 2) {
      c += INCREMENT
    } else {
      c = (-INCREMENT * 5) // reset to a bit less than 0 to show reset state
    }
  }, INTERVAL_DELAY)
}


const createWindow = () => {
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    // frame: false,
    titleBarStyle: 'customButtonsOnHover',
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })

  const menu = Menu.buildFromTemplate([
    {
      label: app.name,
      submenu: [
        {
          click: () => mainWindow.webContents.send('update-counter', 1),
          label: 'Increment'
        },
        {
          click: () => mainWindow.webContents.send('update-counter', -1),
          label: 'Decrement'
        }
      ]
    }
  ])
  
  Menu.setApplicationMenu(menu);
  mainWindow.loadFile('index.html')
  // progressEvent(mainWindow);
  return mainWindow;
}

// const dockMenu = Menu.buildFromTemplate([
//   {
//     label: 'New Window',
//     click () { console.log('New Window') }
//   }, {
//     label: 'New Window with Settings',
//     submenu: [
//       { label: 'Basic' },
//       { label: 'Pro' }
//     ]
//   },
//   { label: 'New Command...' }
// ]);


// const menu = new Menu()
// menu.append(new MenuItem({
//   label: 'Electron',
//   submenu: [{
//     role: 'help',
//     accelerator: process.platform === 'darwin' ? 'Alt+Cmd+I' : 'Alt+Shift+I',
//     click: () => { console.log('Electron rocks!') }
//   }]
// }))
// Menu.setApplicationMenu(menu)


function showNotification () {
  const NOTIFICATION_TITLE = 'Basic Notification'
  const NOTIFICATION_BODY = 'Notification from the Main process'
  new Notification({ title: NOTIFICATION_TITLE, body: NOTIFICATION_BODY }).show()
}


// 主线程调用接口，渲染进程接收数据
async function getRequest(mainWindow) {
  try {
    const dataParams = { captchaType: "blockPuzzle" };
    // const urlPath = 'https://api.saas.test.tynd.com/tyndall-saas/admin-api/v1/system/captcha/get';
    const urlPath = 'https://gw-yxm.liangkebang.net/vcc/usercenter/captcha_type';
    const beforeData = await postRequest(urlPath, dataParams);
    mainWindow.webContents.send('before-data', beforeData);
  } catch(error) {
    mainWindow.webContents.send('before-data', { code: 1, message: error.message });
  }
}


app.whenReady().then(() => {
  installExtension(REACT_DEVELOPER_TOOLS)
    .then((name) => console.log(`Added Extension:  ${name}`))
    .catch((err) => console.log('An error occurred: ', err));
  // if (process.platform === 'darwin') {
  //   app.dock.setMenu(dockMenu);
  // }

  ipcMain.on('show-notification', showNotification);


  ipcMain.handle('dark-mode:toggle', () => {
    if (nativeTheme.shouldUseDarkColors) {
      nativeTheme.themeSource = 'light'
    } else {
      nativeTheme.themeSource = 'dark'
    }
    return nativeTheme.shouldUseDarkColors
  })

  ipcMain.handle('dark-mode:system', () => {
    nativeTheme.themeSource = 'system'
  })
  

  console.log('=================>初始化！');
  const win = createWindow();

  win.webContents.openDevTools();

  // 发送请求
  getRequest(win);

  // 模式 3：主进程到渲染器进程
  ipcMain.on('counter-value', (_event, value) => {
    console.log('===============>counter-value', value);
  })


  // 模式 2：渲染器进程到主进程（双向）
  ipcMain.handle('dialog:openFile', handleFileOpen)


  // 模式 1：渲染器进程到主进程（单向）, ipcRenderer.send 发送，ipcMain.on 接收。
  ipcMain.on('set-title', (event, title) => {
    const webContents = event.sender
    const win = BrowserWindow.fromWebContents(webContents)
    win.setTitle(title)
  })

  ipcMain.handle('ping', () => {
    return '渲染进程触发到主进程';
  });

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
});


// before the app is terminated, clear both timers
app.on('before-quit', () => {
  clearInterval(progressInterval)
});

app.on('window-all-closed', () => {
  console.log('================>关闭所有窗口！', process.platform);
  if (process.platform !== 'darwin') app.quit()
});